/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fun.tan90.easy.binlog.plugin.rocketmq.listener;


import cn.hutool.json.JSONUtil;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputResEnum;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEvent;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEventRes;
import fun.tan90.easy.binlog.plugin.common.listener.BinlogEventPluginListener;
import fun.tan90.easy.binlog.plugin.common.model.BinlogData;
import fun.tan90.easy.binlog.plugin.common.model.BinlogOutputRule;
import fun.tan90.easy.binlog.plugin.rocketmq.constants.RocketmqPluginConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.noear.dami.Dami;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * description 应用初始化后置处理器，防止 spring 事件被多次执行
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/8/17 8:31
 */
@Slf4j
public class RocketmqEventProcessor implements BinlogEventPluginListener, ApplicationListener<ApplicationReadyEvent> {

    private final AtomicBoolean initialized = new AtomicBoolean(false);

    private final LoadingCache<String, DefaultMQProducer> rocketmqProducerCache;

    public RocketmqEventProcessor(LoadingCache<String, DefaultMQProducer> rocketmqProducerCache) {
        this.rocketmqProducerCache = rocketmqProducerCache;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (initialized.compareAndSet(false, true)) {
            Dami.<BinlogDataEvent, BinlogDataEventRes>bus().listen(DamiEventConstants.BINLOG_EVENT_TOPIC + outputType(), payload -> {
                BinlogDataEvent binlogDataEvent = payload.getContent();
                String masterCode = binlogDataEvent.getMasterCode();
                List<BinlogData> binlogDataList = binlogDataEvent.getBinlogDataList();
                List<BinlogOutputRule> binlogOutputTypeRules = binlogDataEvent.getBinlogOutputRules();
                for (BinlogOutputRule binlogOutputRule : binlogOutputTypeRules) {
                    String outputRuleCountId = binlogOutputRule.getOutputRuleCountId();
                    String outputCode = binlogOutputRule.getOutputCode();
                    DefaultMQProducer producer = rocketmqProducerCache.get(outputCode);
                    if (producer != null) {
                        for (BinlogData binlogData : binlogDataList) {
                            if (filterOutput(binlogOutputRule, binlogData)) {
                                Message message = new Message(RocketmqPluginConstants.TOPIC, masterCode, JSONUtil.toJsonStr(binlogData).getBytes());
                                try {
                                    producer.send(message, new SendCallback() {
                                        @Override
                                        public void onSuccess(SendResult sendResult) {
                                            MessageQueue messageQueue = sendResult.getMessageQueue();
                                            log.info("onSuccess SendStatus {} MsgId {} BrokerName {} QueueId {}", sendResult.getSendStatus(), sendResult.getMsgId(), messageQueue.getBrokerName(), messageQueue.getQueueId());
                                            reply(payload, outputRuleCountId, OutputResEnum.SUCCESS);
                                        }

                                        @Override
                                        public void onException(Throwable e) {
                                            reply(payload, outputRuleCountId, OutputResEnum.ERROR);
                                            log.error("onException msg {}", e.getMessage());
                                            e.printStackTrace();
                                        }
                                    });
                                } catch (Exception e) {
                                    reply(payload, outputRuleCountId, OutputResEnum.ERROR);
                                    log.error("rocketmq 发送失败 {}", e.getMessage());
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    public String outputType() {
        return OutputTypeEnum.ROCKETMQ.getOutputType();
    }
}
